import React, { ReactElement, useMemo, useRef, useEffect } from 'react';
import { ScrollView, DeviceEventEmitter, View, AppState } from 'react-native';
import { NavigationScreenProps } from 'react-navigation';
import BackgroundJob from 'react-native-background-job';
import X5WebView from 'react-native-webview-x5';

import styles from './style';
import CourseList from './components/CourseList';
import Person from './components/Person';
import Tab from './components/Tab';
import Provider, { Store } from './reducer';
import {
  setScroll,
  setCurrentTab,
  reset,
  backAction,
  setTabs,
  showTabEvent,
  getUserLessonResourceIds,
  getGrayConfig
} from './actions';
import { TABS, BACK_TO_TAB_NAV, TabId } from './constant';
import Discovery from './components/Discovery';
import { getIsOpenGuestEntry } from '../../store/appConfig';
import { codePushUpdate } from '../../util/codepush';
import {
  continueDownload,
  getCurrentDownloadVideoTask,
  deleteOtherVideoTask
} from '../../util/videoDownload/videoDownloadManage';
import { getAllStoreVideoTasks } from '../../util/videoDownload/videoDownloadStore';
import { dlVideoDeleteOther } from '../../util/download/downloadOperation';
import { getAllDlVideos } from '../../util/download/downloadStore';
import { DEBUG, isIOS } from '../../constant';
import { sendFrontLog } from './components/Person/components/SendLog';
import Log from '../../common/log';

const TAG = 'AppStateChangeLog';

export default (props: NavigationScreenProps): ReactElement => {
  const { navigation } = props;
  const scroll = useRef<ScrollView>(null);

  const isOpenGuestEntry = getIsOpenGuestEntry();

  const appStatusChange = (): void => {
    const appState = AppState.currentState;
    Log.i(TAG, JSON.stringify({ event: 'appStateChange', appState }));
    const downloadTask = getCurrentDownloadVideoTask();

    if (appState === 'background' || appState === 'inactive') {
      if (downloadTask && isIOS) downloadTask.startDownloadAllTs();
    } else if (appState === 'active') {
      backAction();
      // if (downloadTask && isIOS) downloadTask.stopDownloadAllTs();
    }
  };

  useEffect((): (() => void) => {
    const backgroundSchedule = {
      jobKey: 'continueDownload',
      allowExecutionInForeground: true,
      period: 5000,
      exact: true,
      allowWhileIdle: true,
      override: false,
      networkType: BackgroundJob.NETWORK_TYPE_ANY
    };
    if (isIOS) {
      continueDownload();
    } else {
      BackgroundJob.schedule(backgroundSchedule);
    }
    AppState.addEventListener('change', appStatusChange);

    // 删除老版本视频
    getAllDlVideos().forEach(({ id }): void => {
      dlVideoDeleteOther(id);
    });

    getAllStoreVideoTasks().forEach(({ id, urls }): void => {
      if (urls.length > 1) {
        deleteOtherVideoTask(id);
      }
    });

    /**
     * Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
     * 刚进首页发送日志，部分机型会报错，activity为null，如果做错误拦截，则日志不会发送成功
     * 延时发送，可以避免这个问题
     */
    const timer = setTimeout((): void => {
      if (!DEBUG) {
        sendFrontLog(false);
      }
    }, 15 * 1000);

    return (): void => {
      AppState.removeEventListener('change', appStatusChange);
      if (timer) {
        clearTimeout(timer);
      }
    };
  }, []);

  useEffect((): (() => void) => {
    setScroll(scroll);
    setTabs(isOpenGuestEntry ? TABS : [TABS[1], TABS[2]]);
    showTabEvent(isOpenGuestEntry ? TABS[0].id : TABS[1].id);

    const subscription = DeviceEventEmitter.addListener(
      BACK_TO_TAB_NAV,
      ({ id }): void => {
        const selectedTab = TABS.find((tab): boolean => tab.id === id);
        if (selectedTab) {
          setCurrentTab(selectedTab);
        }
      }
    );

    const didFocusSubscription = navigation.addListener(
      'didFocus',
      (): void => {
        backAction();
        getGrayConfig();
      }
    );

    codePushUpdate();
    getUserLessonResourceIds();
    getGrayConfig();

    return (): void => {
      subscription.remove();
      didFocusSubscription.remove();
    };
  }, [isOpenGuestEntry, navigation]);

  return useMemo(
    (): ReactElement => (
      <Provider style={styles.container}>
        <Store.Consumer>
          {(res): ReactElement => {
            const { state } = res;
            const { tabs } = state;

            return (
              <View style={styles.container}>
                <ScrollView
                  ref={scroll}
                  style={styles.content}
                  pagingEnabled
                  horizontal
                  showsHorizontalScrollIndicator={false}
                  scrollEnabled={false}
                  onContentSizeChange={(): void => {
                    reset();
                  }}
                >
                  {isIOS ? null : (
                    <X5WebView
                      style={styles.webview}
                      source={{
                        uri: 'http://h5.mifengxiaoban.com/aikid'
                      }}
                      androidLayerType="software"
                    />
                  )}
                  {tabs.map(
                    (tab): ReactElement => {
                      if (tab.id === TabId.Discovery) {
                        return <Discovery key={tab.id} />;
                      }
                      if (tab.id === TabId.Course) {
                        return <CourseList key={tab.id} />;
                      }
                      if (tab.id === TabId.Mine) {
                        return <Person key={tab.id} />;
                      }
                      return <View key={tab.id} />;
                    }
                  )}
                </ScrollView>
                <Tab />
              </View>
            );
          }}
        </Store.Consumer>
      </Provider>
    ),
    []
  );
};
